package org.opens.javaskill.design;

/**
 * 功能:
 *      责任链模式的demo-模拟日志等级记录日志.
 */
public class ChainOfResponsibilityPattern {

    public static void main(String[] args) {
        AbstractLogger infoLogger = new InfoLogger();
        AbstractLogger debugLogger = new DebugLogger();
        AbstractLogger errorLogger = new ErrorLogger();

        debugLogger.setNext(infoLogger);
        errorLogger.setNext(debugLogger);

        errorLogger.logMessage(LoggerLevel.INFO, "日志1");
        errorLogger.logMessage(LoggerLevel.DEBUG, "日志2");
        errorLogger.logMessage(LoggerLevel.ERROR, "日志3");
        errorLogger.logMessage(4, "日志4");
    }

}

abstract class AbstractLogger {

    protected int level;

    protected AbstractLogger abstractLogger;

    public void setNext(AbstractLogger abstractLogger) {
        this.abstractLogger = abstractLogger;
    }

    public void logMessage(int level, String message) {
        if ( this.level == level ) {
            write(message);
        } else if ( this.abstractLogger != null ) {
            abstractLogger.logMessage(level, message);
        } else {
            System.out.println("没有下一个处理器了");
        }
    }

    abstract void write(String message);

}

interface LoggerLevel {

    public static final int INFO = 1;

    public static final int DEBUG = 2;

    public static final int ERROR = 3;

}

class InfoLogger extends AbstractLogger {

    public InfoLogger() {
        this.level = LoggerLevel.INFO;
    }

    @Override
    void write(String message) {
        System.out.println("Info logger: " + message);
    }

}

class DebugLogger extends AbstractLogger {

    public DebugLogger() {
        this.level = LoggerLevel.DEBUG;
    }

    @Override
    void write(String message) {
        System.out.println("Debug logger: " + message);
    }

}

class ErrorLogger extends AbstractLogger {

    public ErrorLogger() {
        this.level = LoggerLevel.ERROR;
    }

    @Override
    void write(String message) {
        System.out.println("Error logger: " + message);
    }

}
